import requests
import json


def request_text_audit(article_text):
    """
    敏感词检测
    """
    host = "http://123.57.94.186:8020"
    path = "/ai-chat-provider/provider/api/audit"
    url = host + path

    payload = json.dumps({
        "content": article_text
    })
    headers = {
        'Content-Type': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    if response.status_code == 200:
        try:
            audit_array = []
            data_response = json.loads(response.text)
            data_results = data_response.get("data", {})[0].get("results", {})
            if len(data_results) > 0:
                results_info = data_results[0]
                if results_info.get("suggestion", "") == "block":
                    # 有敏感词
                    details_array = results_info.get("details", [])
                    for item in details_array:
                        for ctx in item.get("contexts", []):
                            name = ctx.get("context", "")
                            audit_array.append(name)
                    return (True, audit_array)
                else:
                    return (True, audit_array)
            else:
                return (True, audit_array)
        except Exception as e:
            return (False, f"敏感词json异常:{response.text}")
    else:
        return (False, f"敏感词status_code异常:{response.status_code}")


def exact_match_audit(article_text, audit_array):
    """
    精确匹配
    """
    exact_matched_audit = []
    for audit_word in audit_array:
        if audit_word in article_text:
            exact_matched_audit.append(audit_word)
    if len(exact_matched_audit) > 0:
        return exact_matched_audit
    else:
        return []
